#!/usr/bin/ruby
# -*- coding: utf-8 -*-

require 'cgi'
require 'dbi'

DBIURL="dbi:Mysql:macaddress:localhost"
DBUSER="macaddress"
DBAUTH="macaddress"

def getmacstr(mac)
  str = ""
  mac.each { |val|
    str << sprintf("%02x:", val)
  }
  return str.chop
end

def put_list(cgi, dbh)
  sh = dbh.execute("SELECT name,address FROM macaddress;")
  table = nil
  if sh.fetchable? then
    table = cgi.tr() { cgi.td() { "ホスト" } + cgi.td() { "アドレス" } }
    sh.each { |row|
      table << cgi.tr() {
        cgi.td() { row[0] } +
        cgi.td() { row[1] }
      }
    }
    sh.finish
  end
  cgi.out({"caraset" => "utf-8"}) {
    cgi.html({"lang" => "ja"}) {
       cgi.head {
        cgi.title{"MAC Address List"}
      } +
      cgi.body() {
        cgi.form() {
          cgi.text_field("host") +
          cgi.submit("登録")
        } + cgi.table('border' => '1') { table }
      }
    }
  }
end


cgi = CGI.new("html4")
host = cgi["host"]
dbh = DBI.connect(DBIURL, DBUSER, DBAUTH)
dbh.do("use macaddress;");
if (host.empty?) then
  put_list(cgi, dbh)
else
  mac = [0x10, 0x00, 0x00, 0x00, 0x00, 0x00]
  while true do
    s = Time.now.to_i
    mac[3] = (s >> 16) & 0xff
    mac[4] = (s >> 8) & 0xff
    mac[5] = s & 0xff
    macstr = getmacstr(mac)
    sh = dbh.execute("SELECT name FROM macaddress WHERE address='#{macstr}';")
    break if sh.fetchable?
  end
  dbh.do("INSERT INTO macaddress(name, address) VALUES('#{host}', '#{getmacstr(mac)}');")
  put_list(cgi, dbh)
end

